﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using MeTalker.Aide.Forms;
using MeTalker.SDK.Core;
using MeTalker.Aide.data;

namespace MeTalker.Aide
{
    internal delegate void ShowFormHandler(object sender,Form form);
    internal class MeAppContext : MeApplicationBase
    {  
        void InitializeComponent()
        {
        }

        #region 构造
        public MeAppContext()
        {
            InitializeComponent();
            formHandler = new ShowFormHandler(ShowForm);
            mTimerWin = new System.Threading.Timer(TimerCallBack, null, 1000, 500);
            mTimer = new Timer();
            mTimer.Tick += new EventHandler(mTimer_Tick);
            mTimer.Interval = UtilHelper.CHECK_USER_INTERVAL;
            mTimer.Enabled = true;
        }
        #endregion

        void TimerCallBack(object sender)
        {
            try
            {
              bool d =  WindowControl.EnumWindows(FindHwnd, 0);
            }
            catch { }
        }

        void CommandCallBack(object sender, TalkerState talkerState, object state)
        { 
        
        }
        bool FindHwnd(IntPtr hwnd, int a)
        {
            try
            {
                StringBuilder builder2 = new StringBuilder(0x100);
                WindowControl.GetWindowText(hwnd, builder2, 0x100);
                string title = builder2.ToString();

                lock (this.procs)
                {
                    int indexTitle = title.IndexOf(UtilHelper.TITLE_MAIN);
                    if (indexTitle<=0)
                        indexTitle = title.IndexOf(UtilHelper.TITLE_MAIN_2012);
                    if (indexTitle > 1)
                    {
                        string account = title.Substring(0, indexTitle);
                        int pid;
                        WindowControl.GetWindowThreadProcessId(hwnd, out pid);
                        if (procs.ContainsKey(pid))
                        {
                        }
                        else
                        {
                            UserConfig userConfig = null;
                            try
                            {
                                var d = from temp in DataFactory.SystemConfig.UserConfigs where temp.Account.Equals(account) select temp;
                                userConfig = d.FirstOrDefault();
                            }
                            catch { }

                            ProcInfo proc = new ProcInfo();
                            proc.Alias = account;
                            proc.Account = account;
                            proc.MainhWnd = hwnd;
                            proc.Pid = pid;
                            proc.Title = title;
                            proc.State = userConfig != null ? userConfig.WorkMode : TalkerState.AutoChatAid;
                            procs.Add(pid, proc);
                        }
                        return true;
                    }

                    indexTitle = title.IndexOf(UtilHelper.TITLE);
                    if (indexTitle > 1)
                    {
                        int pid;
                        WindowControl.GetWindowThreadProcessId(hwnd, out pid);
                        string account = title.Substring(0, indexTitle);

                        bool isVisible = WindowControl.IsWindowVisible(hwnd);
                        if (procs.ContainsKey(pid) && isVisible)
                        {
                            ProcInfo proc = procs[pid];
                            proc.Alias = account;
                            proc.ChildhWnd = hwnd;
                        }
                        return true;
                    }
                }
            }
            catch(Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("FindHwnd", ex);
            }
            return true;
        }

        int count = 0;

        void mTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                List<KeyValuePair<int, ProcInfo>> procList = procs.ToList();
                try
                {
                    foreach (var proc in procList)
                    {

                        if (IsWindExist(proc.Value.Title))
                        {
                            AddMenuItem(proc.Value);
                        }
                        else
                        {
                            RemoveMenuItem(proc.Value);
                        }
                    }
                }
                catch { }


                foreach (var tempVK in procList)
                {
                    lock (this)
                    {
                        ProcInfo proc = tempVK.Value;
                        WindowControl.RECT rect;
                        if (TalkerHelper.Check(proc.Alias, out rect) == true && proc.ChildhWnd != IntPtr.Zero)
                        {
                            Start(proc, proc.State);
                        }
                    }
                }
                count++;
                if (count > UtilHelper.HEART_COUNT_INTERVAL)
                {
                    count = 0;
                    SetHeartbeat();
                }
            }
            catch { }
        }

        bool IsWindExist(string title)
        {
            if (WindowControl.FindWindow(null, title) == IntPtr.Zero) {
                return false;
            }
            return true;
        }

        void ShowForm(object sender, Form form)
        {
            ShowFormHandler del = delegate(object sender1, Form form1)
            {
                form.Show();
            };
            contextMenuStrip.BeginInvoke(del, new object[] { sender, form });
        }
    }

   internal class ProcInfo {
       internal int Pid { get; set; }
       internal IntPtr ChildhWnd { get; set; }
       internal IntPtr MainhWnd { get; set; }
       internal string Alias { get; set; }
       internal string Account { get; set; }
       internal TalkerState State { get; set; }
       internal string Title { get; set; }
    }
}